import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Route} from "@angular/router";
import {Application} from "../../shared/model/application";
import {CamSearchService} from "../../shared/service/cam-search.service";
import {Condition} from "../../shared/model/condition";
import MTSConstants from "../../shared/config/config";
import {BackCode} from "../../shared/model/backCode";
import {Http, RequestOptions} from "@angular/http";

//import {CamSearchService} from "../../shared/service/cam-search.service";
@Component({
  selector: 'app-cam-search-table',
  templateUrl: './cam-search-table.component.html',
  styleUrls: ['./cam-search-table.component.css']
})
export class CamSearchTableComponent implements OnInit {

  servicename:string;
  selectedData = [];
  selectMeeting:Array<string> = [];
  allCheckbox:boolean = false;
  userId:string = this.routerInfo.snapshot.queryParams["userId"];     //当前登陆者ID

  //查询参数
  vehicleName:string = "";  //车型名称
  phase:string = "day";     //时间段  day(今天)， week(本周），month（本月），all（全部）
  licenseNumber:string = "";       //车牌号
  status:number = -1;       //用车申请状态  0：审批中（流程进行中）；1：已审批（流程正常结案）；2：已撤销（申请人操作）；3：已终止（审批人操作） 4：取消（结案之后，派车之前，申请人可以取消出车申请）'
  applicant :string = ""; //申请人员（普通员工默认为登录者自己，车辆管理员可以选择）;
  starttime:string = "";  //开始时间
  endtime:string = "";  //结束时间

  //用车申请列表
  camApplyList:Application[] = [];

  constructor(private camSearchService:CamSearchService,
              private routerInfo:ActivatedRoute,
              private http:Http
  ) { }
  _current = 1;
  _pageSize = 10;
  _total = 1;
  _dataSet = [];
  _loading = true;

  ngOnInit() {
    this.refreshData();
    this.camSearchService.change.subscribe((info:Condition)=>{
      this.getCondition(info);
      this.refreshData();
    });
  }

  //参数传递赋值
  getCondition(condition:Condition){
    this.vehicleName = condition.vehicelName;
    this.userId = condition.userId;
    this.phase = condition.phase;
    this.licenseNumber = condition.licenseNumber;
    this.applicant = condition.applicant;
    this.status = condition.status;
    this.starttime = condition.starttime;
    this.endtime = condition.endtime;
  }


  //选择框
  _allChecked = false;
  // _indeterminate = false;
  _displayData: Array<any> = [];
  _checkedNumber = 0;
  _checkInfo= [];
  checkAllInfo = [];


  _checkAll(value) {
    if (value) {
      // this._displayData.forEach(data => data.checked = true);
      for(let i =0;i<this._displayData.length;i++){
        if(this._displayData[i].status!=0){
          this._displayData[i].checked = true;
        }
      }
    } else {
      this._displayData.forEach(data => data.checked = false);
      for(let i=0;i<this._displayData.length;i++){
        let numb = this.checkAllInfo.indexOf(this._displayData[i].oid);
        if(numb!=-1){
          this.checkAllInfo.splice(numb,1);
        }
      }
    }
    this._refreshStatus("","");
  };

  //当前页checkbox选中判断
  _refreshStatus(event,oid) {
    //全选判断
    if(this._displayData.length>0){
      let count:number = 0;
      let checkNumb:number = 0;
      for(let i =0;i<this._displayData.length;i++){
        if(this._displayData[i].status !=0){
          count++;
          if(this._displayData[i].checked == true){
            checkNumb++;
          }
        }
      }
      if(checkNumb!=0 && count==checkNumb){
        this._allChecked = true;
      }else{
        this._allChecked = false;
      }
    }
    this._checkedNumber = this._dataSet.filter(value => value.checked).length;
    this._checkInfo = this._dataSet.filter(value => value.checked);  //存放选中行的信息
    //判断是否有checkbox取消事件
    if(event==false){
      let numb = this.checkAllInfo.indexOf(oid);
      if(numb!=-1){
        this.checkAllInfo.splice(numb,1);
      }
    }
  };

  _displayDataChange($event) {
    this._displayData = $event;
  };

  //选择判断
  select(selectedData:any,currentData:any){
    let selectInfo = [];
    if(selectedData){
      for(var i=0;i<currentData.length;i++){
        for(var j=0;j<selectedData.length;j++){
          if(currentData[i].oid == selectedData[j]){
            selectInfo.push(currentData[i]);
          }
        }
      }
      selectInfo.forEach(data => data.checked = true);
    }
  }

  //刷新数据
  refreshData(reset = false) {
    if (reset) {
      this._current = 1;
    }
    this._loading = true;
    this.getCamApplyInfo();
  };

  //获取用车申请信息
  getCamApplyInfo(){
    let camname = "";
    if(this.licenseNumber ===""){
      camname = this.vehicleName;
    }else{
      camname = "";
    }
    let exclude = "";
    if(this.status == -1){
      exclude = "2,3";
    }else if(this.status == 0){
      exclude = "1,2,3,4";
    }else if(this.status == 1){
      exclude = "0,2,3,4";
    }else if(this.status == 2){
      exclude = "0,1,3,4";
    }else if(this.status == 3){
      exclude = "0,1,2,4";
    }else if(this.status == 4){
      exclude = "0,2,3,1";
    }

    this.camSearchService.getCamApplyInfo(this._current,this._pageSize,this.applicant,this.phase,camname,this.licenseNumber,exclude).then(res=>{
      this.camApplyList = res.list;
      let applyoid="";
      this.allCheckbox = false;
      for(let i=0;i<this.camApplyList.length;i++){
        applyoid = this.camApplyList[i].oid;
        //判断用车申请记录状态
        let statusname = "";
        let date = new Date();
        this.camApplyList[i].cancel= false;
        switch (this.camApplyList[i].status) {
          case 0:
            statusname = "审批中";
            break;
          case 1:
            statusname = "已审批";
            let applicantID = this.camApplyList[i].applicant.split("_")[0];
            if(date < new Date(this.camApplyList[i].starttime) && applicantID == this.userId){
              this.camApplyList[i].cancel = true;
            }
            break;
          case 2:
            statusname = "已撤销";
            break;
          case 3:
            statusname = "已终止";
            break;
          case 4:
            statusname = "已取消";
            break;
          default:
            statusname = "";
            break;
        }
        this.camApplyList[i].statusname = statusname;

        //判断全选框是否显示
        if(this.camApplyList[i].status != 0){
          this.allCheckbox = true;
        }
      }
      this._dataSet = res.list;
      this._loading = false;
      this._total = res.total;
      this._displayData = res.list;

      //查询选中
      for(var i=0;i<this._checkInfo.length;i++){
        if(this.checkAllInfo.indexOf(this._checkInfo[i].oid) == -1){
          this.checkAllInfo.push(this._checkInfo[i].oid);
        }
      }
      this.select(this.checkAllInfo,this._dataSet);

      //全选判断
      this._refreshStatus("","");
    });
  }

  /*getCamApplyInfo() {
    this.allCheckbox = false;
    for(let i=0;i<this.camApplyList.length;i++){
      //判断会议记录状态
      let statusname = "";
      let date = new Date();
      this.camApplyList[i].cancel= false;
      switch (this.camApplyList[i].status) {
        case 0:
          statusname = "审批中";
          break;
        case 1:
          statusname = "已审批";
          if(date < new Date(this.camApplyList[i].endtime )&& date > new Date(this.camApplyList[i].starttime)){
            this.camApplyList[i].cancel = true;
          }
          break;
        case 2:
          statusname = "已撤销";
          break;
        case 3:
          statusname = "已终止";
          break;
        case 4:
          statusname = "已取消";
          break;
        default:
          statusname = "";
          break;
      }
      this.camApplyList[i].statusname = statusname;

      //判断全选框是否显示
      if(this.camApplyList[i].status != 0){
        this.allCheckbox = true;
      }
    }
    this._dataSet = this.camApplyList;
    this._loading = false;
    this._total = this.camApplyList.length;
    this._displayData = this.camApplyList;

    //查询选中
    for(var i=0;i<this._checkInfo.length;i++){
      if(this.checkAllInfo.indexOf(this._checkInfo[i].oid) == -1){
        this.checkAllInfo.push(this._checkInfo[i].oid);
      }
    }
    this.select(this.checkAllInfo,this._dataSet);

    //全选判断
    this._refreshStatus("","");
  }*/
  //取消
  cancel(application:Application){
    if(confirm("取消后将无法恢复，确定要取消吗？\n")) {
      application.status = 4;
      this.camSearchService.cancelApplication(application.processsn).then(res => {
        if (res.code > 0) {
          alert("用车申请取消成功！");
        } else {
          alert("用车申请取消失败！");
        }

        this.refreshData();
      });
    }
  }
  // //删除
  delInfo(){
    //将当前页所选用车申请信息插入所有选择信息变量checkAllInfo中
    for(var i=0;i<this._checkInfo.length;i++){
      if(this.checkAllInfo.indexOf(this._checkInfo) == -1){
        this.checkAllInfo.push(this._checkInfo[i].oid);
      }
    }
    if(this.checkAllInfo.length>0){
      if(confirm("共选择"+this.checkAllInfo.length+"条用车申请信息，删除后将无法恢复，确定要删除吗？\n")){
        for(let i=0;i<this.checkAllInfo.length;i++){
          if(this.checkAllInfo[i].cancel == true ) {
            // this.camSearchService.cancelApplication(this.checkAllInfo[i]);
            const url = `${MTSConstants.HOSTUser}application/return/abort?processsn=${this.checkAllInfo[i]}`;
            const headers = MTSConstants.headers;//spring的restful接口用这个
            return this.http.post(url,headers)
              .toPromise()
              .then((res) => { alert("删除成功！\n");
                this.checkAllInfo = [];
                this._checkInfo = [];
                this._current = 1;
                this.refreshData();})
              .catch((error: any) => {return this.handleError('cancelApplication',error);});
          }
          // this.camSearchService.delApplication(this.checkAllInfo[i]);
          const url = `${MTSConstants.HOSTUser}application/${this.checkAllInfo[i]}`;
          const headers = MTSConstants.headers;//spring的restful接口用这个
          const options = new RequestOptions({ headers: headers });
          return this.http.delete(url, options)
            .toPromise()
            .then((res) => {
              this.checkAllInfo = [];
              this._checkInfo = [];
              this._current = 1;
              this.refreshData();})
            .catch((error: any) => {return this.handleError('deleteRoom',error);});

        }

      }
    }else{
      alert("请至少选择一条用车申请信息！\n");
    }
  }

  handleError(functionName:string,error: any): Promise<any> {
    console.error(`服务 : ${this.servicename} , 函数 : ${functionName} 。发生错误 : `, error);
    return Promise.reject(error.message || error);
  }
}
